<template>
  <div class="profile-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>个人中心</h2>
      <p>管理您的个人信息和账户设置</p>
    </div>

    <t-row :gutter="24">
      <!-- 左侧个人信息卡片 -->
      <t-col :span="8">
        <t-card title="个人信息" class="profile-card">
          <div class="profile-info">
            <div class="avatar-section">
              <t-avatar size="80px" class="profile-avatar">
                {{ userStore.userName.substring(0, 1) }}
              </t-avatar>
              <t-button variant="text" size="small" class="change-avatar-btn">
                <t-icon name="camera" />
                更换头像
              </t-button>
            </div>
            
            <div class="info-list">
              <div class="info-item">
                <label>用户名：</label>
                <span>{{ userStore.userName }}</span>
              </div>
              <div class="info-item">
                <label>邮箱：</label>
                <span>{{ userInfo.email || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>手机号：</label>
                <span>{{ userInfo.phone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <label>角色：</label>
                <t-tag v-for="role in userStore.userRoles" :key="role" theme="primary" size="small">
                  {{ getRoleDisplayName(role) }}
                </t-tag>
              </div>
              <div class="info-item">
                <label>注册时间：</label>
                <span>{{ formatDate(userInfo.createdAt) }}</span>
              </div>
              <div class="info-item">
                <label>最后登录：</label>
                <span>{{ formatDate(userInfo.lastLoginAt) }}</span>
              </div>
            </div>
          </div>
        </t-card>
      </t-col>

      <!-- 右侧设置区域 -->
      <t-col :span="16">
        <t-tabs v-model="activeTab" class="profile-tabs">
          <!-- 基本信息编辑 -->
          <t-tab-panel value="basic" label="基本信息">
            <t-card>
              <t-form
                ref="basicFormRef"
                :model="basicForm"
                :rules="basicFormRules"
                label-width="100px"
                class="profile-form"
              >
                <t-form-item label="用户名" name="userName">
                  <t-input v-model="basicForm.userName" placeholder="请输入用户名" />
                </t-form-item>
                
                <t-form-item label="邮箱" name="email">
                  <t-input v-model="basicForm.email" placeholder="请输入邮箱地址" />
                </t-form-item>
                
                <t-form-item label="手机号" name="phone">
                  <t-input v-model="basicForm.phone" placeholder="请输入手机号码" />
                </t-form-item>
                
                <t-form-item label="个人简介" name="bio">
                  <t-textarea 
                    v-model="basicForm.bio" 
                    placeholder="请输入个人简介"
                    :maxlength="200"
                    :autosize="{ minRows: 3, maxRows: 5 }"
                  />
                </t-form-item>
                
                <t-form-item>
                  <t-button theme="primary" @click="handleUpdateBasicInfo" :loading="updating">
                    保存修改
                  </t-button>
                  <t-button variant="outline" @click="resetBasicForm">
                    重置
                  </t-button>
                </t-form-item>
              </t-form>
            </t-card>
          </t-tab-panel>

          <!-- 密码修改 -->
          <t-tab-panel value="password" label="修改密码">
            <t-card>
              <t-form
                ref="passwordFormRef"
                :model="passwordForm"
                :rules="passwordFormRules"
                label-width="100px"
                class="profile-form"
              >
                <t-form-item label="当前密码" name="currentPassword">
                  <t-input 
                    v-model="passwordForm.currentPassword" 
                    type="password"
                    placeholder="请输入当前密码"
                  />
                </t-form-item>
                
                <t-form-item label="新密码" name="newPassword">
                  <t-input 
                    v-model="passwordForm.newPassword" 
                    type="password"
                    placeholder="请输入新密码"
                  />
                </t-form-item>
                
                <t-form-item label="确认密码" name="confirmPassword">
                  <t-input 
                    v-model="passwordForm.confirmPassword" 
                    type="password"
                    placeholder="请再次输入新密码"
                  />
                </t-form-item>
                
                <t-form-item>
                  <t-button theme="primary" @click="handleUpdatePassword" :loading="updatingPassword">
                    修改密码
                  </t-button>
                  <t-button variant="outline" @click="resetPasswordForm">
                    重置
                  </t-button>
                </t-form-item>
              </t-form>
            </t-card>
          </t-tab-panel>

          <!-- 系统设置 -->
          <t-tab-panel value="settings" label="系统设置">
            <t-card>
              <div class="settings-section">
                <h4>界面设置</h4>
                <div class="setting-item">
                  <label>主题模式：</label>
                  <t-radio-group v-model="themeMode" @change="handleThemeChange">
                    <t-radio value="light">浅色模式</t-radio>
                    <t-radio value="dark">深色模式</t-radio>
                    <t-radio value="auto">跟随系统</t-radio>
                  </t-radio-group>
                </div>
                
                <div class="setting-item">
                  <label>侧边栏默认状态：</label>
                  <t-switch 
                    v-model="sidebarCollapsed" 
                    @change="handleSidebarChange"
                    :label="[sidebarCollapsed ? '折叠' : '展开']"
                  />
                </div>
              </div>

              <t-divider />

              <div class="settings-section">
                <h4>通知设置</h4>
                <div class="setting-item">
                  <label>邮件通知：</label>
                  <t-switch v-model="notificationSettings.email" />
                </div>
                
                <div class="setting-item">
                  <label>短信通知：</label>
                  <t-switch v-model="notificationSettings.sms" />
                </div>
                
                <div class="setting-item">
                  <label>系统消息：</label>
                  <t-switch v-model="notificationSettings.system" />
                </div>
              </div>

              <t-divider />

              <div class="settings-section">
                <h4>安全设置</h4>
                <div class="setting-item">
                  <label>自动登出时间：</label>
                  <t-select v-model="autoLogoutTime" style="width: 200px;">
                    <t-option value="30" label="30分钟" />
                    <t-option value="60" label="1小时" />
                    <t-option value="120" label="2小时" />
                    <t-option value="240" label="4小时" />
                    <t-option value="0" label="永不登出" />
                  </t-select>
                </div>
              </div>

              <div class="settings-actions">
                <t-button theme="primary" @click="handleSaveSettings" :loading="savingSettings">
                  保存设置
                </t-button>
              </div>
            </t-card>
          </t-tab-panel>
        </t-tabs>
      </t-col>
    </t-row>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { MessagePlugin } from 'tdesign-vue-next'

const userStore = useUserStore()
const appStore = useAppStore()

// 当前激活的标签页
const activeTab = ref('basic')

// 用户信息
const userInfo = reactive({
  email: 'admin@example.com',
  phone: '138****8888',
  bio: '系统管理员',
  createdAt: '2024-01-01T00:00:00Z',
  lastLoginAt: new Date().toISOString()
})

// 基本信息表单
const basicFormRef = ref()
const basicForm = reactive({
  userName: '',
  email: '',
  phone: '',
  bio: ''
})

const basicFormRules = {
  userName: [
    { required: true, message: '请输入用户名', type: 'error' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', type: 'error' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', type: 'error' },
    { email: true, message: '请输入正确的邮箱格式', type: 'error' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', type: 'error' }
  ]
}

// 密码修改表单
const passwordFormRef = ref()
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const passwordFormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', type: 'error' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', type: 'error' },
    { min: 6, max: 20, message: '密码长度为6-20个字符', type: 'error' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', type: 'error' },
    {
      validator: (val) => val === passwordForm.newPassword,
      message: '两次输入的密码不一致',
      type: 'error'
    }
  ]
}

// 系统设置
const themeMode = ref('light')
const sidebarCollapsed = ref(false)
const autoLogoutTime = ref('60')
const notificationSettings = reactive({
  email: true,
  sms: false,
  system: true
})

// 加载状态
const updating = ref(false)
const updatingPassword = ref(false)
const savingSettings = ref(false)

// 角色显示名称映射
const roleDisplayNames = {
  'super_admin': '超级管理员',
  'admin': '管理员',
  'user': '普通用户',
  'viewer': '访客'
}

// 获取角色显示名称
const getRoleDisplayName = (role) => {
  return roleDisplayNames[role] || role
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 初始化表单数据
const initFormData = () => {
  basicForm.userName = userStore.userName
  basicForm.email = userInfo.email
  basicForm.phone = userInfo.phone
  basicForm.bio = userInfo.bio
}

// 重置基本信息表单
const resetBasicForm = () => {
  initFormData()
}

// 重置密码表单
const resetPasswordForm = () => {
  Object.assign(passwordForm, {
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })
}

// 更新基本信息
const handleUpdateBasicInfo = async () => {
  const valid = await basicFormRef.value?.validate()
  if (!valid) return

  updating.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新用户信息
    Object.assign(userInfo, {
      email: basicForm.email,
      phone: basicForm.phone,
      bio: basicForm.bio
    })
    
    // 更新store中的用户名
    userStore.userName = basicForm.userName
    
    MessagePlugin.success('个人信息更新成功')
  } catch (error) {
    MessagePlugin.error('更新失败，请重试')
  } finally {
    updating.value = false
  }
}

// 修改密码
const handleUpdatePassword = async () => {
  const valid = await passwordFormRef.value?.validate()
  if (!valid) return

  updatingPassword.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('密码修改成功')
    resetPasswordForm()
  } catch (error) {
    MessagePlugin.error('密码修改失败，请重试')
  } finally {
    updatingPassword.value = false
  }
}

// 主题切换
const handleThemeChange = (value) => {
  appStore.setTheme(value)
  MessagePlugin.success(`已切换到${value === 'light' ? '浅色' : value === 'dark' ? '深色' : '自动'}模式`)
}

// 侧边栏设置
const handleSidebarChange = (value) => {
  appStore.setSidebarCollapsed(value)
}

// 保存系统设置
const handleSaveSettings = async () => {
  savingSettings.value = true
  try {
    // 模拟API调用保存设置
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    MessagePlugin.success('设置保存成功')
  } catch (error) {
    MessagePlugin.error('设置保存失败，请重试')
  } finally {
    savingSettings.value = false
  }
}

// 组件挂载时初始化数据
onMounted(() => {
  initFormData()
  sidebarCollapsed.value = appStore.sidebarCollapsed
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #1f2937;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.profile-card {
  height: fit-content;
}

.profile-info {
  text-align: center;
}

.avatar-section {
  margin-bottom: 24px;
}

.profile-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin-bottom: 12px;
}

.change-avatar-btn {
  display: block;
  margin: 0 auto;
  color: #409eff;
}

.info-list {
  text-align: left;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.info-item label {
  width: 80px;
  font-weight: 500;
  color: #606266;
  flex-shrink: 0;
}

.info-item span {
  color: #303133;
  flex: 1;
}

.profile-tabs {
  background: white;
  border-radius: 6px;
}

.profile-form {
  max-width: 500px;
}

.settings-section {
  margin-bottom: 24px;
}

.settings-section h4 {
  margin: 0 0 16px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 12px 0;
}

.setting-item label {
  font-weight: 500;
  color: #606266;
}

.settings-actions {
  margin-top: 24px;
  text-align: right;
}
</style>
